package com.jdd.modules.system.util;

import com.jdd.common.util.oConvertUtils;
import com.jdd.dao.vo.SysAreaTreeModel;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LS
 * @Date: 2022 - 09 - 23 - 10:37
 * @Description: 查找区域树
 * @version: 1.0
 */
@Component
public class FindsSysAreaChildrenUtil {


    /*找到顶级父类节点，封装到treeList中*/
    public static List<SysAreaTreeModel> findChildren(List<SysAreaTreeModel> records) {
        List<SysAreaTreeModel> treeList = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            SysAreaTreeModel branch = records.get(i);
            if (oConvertUtils.isEmpty(branch.getParentId())) {
                treeList.add(branch);
            }
        }
        getGrandChildren(treeList,records);
        return treeList;
    }

    /**
     * @Description:
     *
      * @param: 所有的有孩子的节点，所有记录
     * @return: null
     * @Author: ls
     * @Date 2022/9/23 10:52
     */
    private static void getGrandChildren(List<SysAreaTreeModel> treeList, List<SysAreaTreeModel> records) {
        for (int i = 0; i < treeList.size(); i++) {
            SysAreaTreeModel model = treeList.get(i);
            for (int j = 0; j < records.size(); j++) {
                SysAreaTreeModel model1 = records.get(j);
                if (model1.getParentId()!=null&&model1.getParentId().equals(model.getKey())){
                    model.getChildren().add(model1);
                }
            }
            getGrandChildren(treeList.get(i).getChildren(),records);
        }
    }

    /**
     * @Description:该方法主要用于将树形结构进行刷新，将没有孩子集合置为空并将是否为叶子置为true，反之置为false
     *
      * @param: treeList--传入树

     * @return: void
     * @Author: ls
     * @Date 2022/9/23 10:55
     */
    public static void setEmptyChildrenAsNull(List<SysAreaTreeModel> treeList){
        for (int i = 0; i < treeList.size(); i++) {
            SysAreaTreeModel model = treeList.get(i);
            if (model.getChildren().size() == 0){
                model.setChildren(null);
                model.setLeaf(true);
            }else{
                setEmptyChildrenAsNull(model.getChildren());
                model.setLeaf(true);
            }
        }
    }
}
